﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraNavBar;
using System.IO;

namespace Reporting
{
    public partial class frmMain : XtraForm
    {
        private int raporCounter = 1;
        private string selectedViewName;
        private string selectedViewCaption;
        private bool parametreli = false;
        string parametre = System.Configuration.ConfigurationSettings.AppSettings["PARAMETRE"];

        public frmMain()
        {
            InitializeComponent();
        }

        private string CreateSql(string viewName)
        {
            string select = "";
            string where = "";
            string oprt = "";
            List<ReportColumn> reportCol = gridControl1.DataSource as List<ReportColumn>;
            foreach (ReportColumn col in reportCol)
            {
                select += col.Name + ',';
            }
            select = select.Remove(select.Length - 1, 1);

            foreach (ReportColumn col in reportCol)
            {
                switch (col.FiltreTipi)
                {
                    case ReportColumn.Filtre.Eşittir:
                        oprt = " = ";
                        break;
                    case ReportColumn.Filtre.Büyüktür:
                        oprt = " > ";
                        break;
                    case ReportColumn.Filtre.BüyükEşittir:
                        oprt = " >= ";
                        break;
                    case ReportColumn.Filtre.Küçüktür:
                        oprt = " < ";
                        break;
                    case ReportColumn.Filtre.KüçükEşittir:
                        oprt = " <= ";
                        break;
                    case ReportColumn.Filtre.İçerir:
                        oprt = " Like ";
                        break;
                    case ReportColumn.Filtre.İçermez:
                        oprt = " Not Like ";
                        break;
                }
                if (!string.IsNullOrEmpty(col.Value))
                {
                    switch (col.Type)
                    {
                        case DbType.Boolean:
                        case DbType.Decimal:
                        case DbType.Int16:
                        case DbType.Int32:
                            where += col.Name + oprt + col.Value + " and ";
                            break;
                        case DbType.DateTime:
                            DateTime tarih = Convert.ToDateTime(col.Value);
                            where += col.Name + oprt + "'" + string.Format("{0}-{1}-{2}", tarih.Year, tarih.Month, tarih.Day) + "' and ";
                            break;
                        case DbType.String:
                            where += col.Name + oprt + "'" + col.Value + "' and ";
                            break;
                    }
                }
            }
            if (where.Length > 0)
            {
                where = " where " + where.Substring(0, where.Length - 4);
                if (parametreli)
                {
                    where += " and PARAMETRE='" + parametre + "'";
                }
                return string.Format("select {0} from {1} {2}", select, viewName, where);
            }
            else
            {
                if (parametreli)
                {
                    return string.Format("select {0} from {1} where PARAMETRE='{2}'", select, viewName, parametre);
                }
                else
                    return "select * from " + viewName;
            }
        }


        public void AddReport(string caption, string viewName)
        {
            navBarControl1.SuspendLayout();

            DevExpress.XtraNavBar.NavBarItem navBarItem1 = new DevExpress.XtraNavBar.NavBarItem();
            navBarItem1.Caption = caption;
            navBarItem1.Name = "Rapor" + raporCounter.ToString();
            navBarItem1.Tag = viewName;
            navBarItem1.LinkClicked += new DevExpress.XtraNavBar.NavBarLinkEventHandler(navBarItem1_LinkClicked);

            this.navBarControl1.Items.AddRange(new DevExpress.XtraNavBar.NavBarItem[] { navBarItem1 });
            this.navBarGroup1.ItemLinks.AddRange(new DevExpress.XtraNavBar.NavBarItemLink[] { new DevExpress.XtraNavBar.NavBarItemLink(navBarItem1) });
            navBarControl1.ResumeLayout();
            raporCounter++;
        }

        void navBarItem1_LinkClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {
            NavBarItem bar = sender as NavBarItem;
            loadReport(bar.Tag.ToString());
            selectedViewName = bar.Tag.ToString();
            selectedViewCaption = bar.Caption;
        }

        public void WriteFile(string caption, string viewName)
        {
            using (StreamWriter sw = new StreamWriter(Application.StartupPath + "\\Raporlar.txt", true))
            {
                sw.WriteLine(string.Format("{0};{1}", caption, viewName));
                sw.Close();
            }
        }

        private void ReadFile()
        {
            if (File.Exists(Application.StartupPath + "\\Raporlar.txt"))
            {
                using (StreamReader sr = new StreamReader(Application.StartupPath + "\\Raporlar.txt"))
                {
                    string line = "";
                    while (sr.Peek() > -1)
                    {
                        line = sr.ReadLine();
                        this.AddReport(line.Split(';')[0], line.Split(';')[1]);
                    }
                    sr.Close();
                }
            }
        }


        private void raporEkleToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmAddReport rep = new frmAddReport();
            rep.ShowDialog(this);
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            ReadFile();
            Combo1.Items.AddRange(Enum.GetNames(typeof(ReportColumn.Filtre)));
        }

        public void loadReport(string viewName)
        {
            parametreli = false;
            List<Column> columns = new Database().GetViewsColumns(viewName, ref parametreli);

            List<ReportColumn> reportCol = new List<ReportColumn>();

            foreach (Column col in columns)
            {
                reportCol.Add(new ReportColumn() { Name = col.Name, Type = col.Type, FiltreTipi = ReportColumn.Filtre.Eşittir, Value = "" });
            }
            gridControl1.DataSource = reportCol;
            gridView1.Columns[2].ColumnEdit = Combo1;

            gridView1.Columns[0].Caption = "Kolon Adı";
            gridView1.Columns[0].OptionsColumn.AllowEdit = false;
            gridView1.Columns[1].Visible = false;

            gridView1.Columns[2].Caption = "Filtre";
            gridView1.Columns[3].Caption = "Değer";
            gridView1.BestFitColumns();

        }

        private void gridView1_FocusedColumnChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedColumnChangedEventArgs e)
        {
            DbType type = (DbType)gridView1.GetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns[1]);
            if (type == DbType.DateTime)
            {
                gridView1.Columns[3].ColumnEdit = DateEdit;
            }
            else
            {
                gridView1.Columns[3].ColumnEdit = null;
            }
        }

        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (gridView1.Columns.Count > 0)
            {
                DbType type = (DbType)gridView1.GetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns[1]);
                if (type == DbType.DateTime)
                {
                    gridView1.Columns[3].ColumnEdit = DateEdit;
                }
                else
                {
                    gridView1.Columns[3].ColumnEdit = null;
                }
            }

        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            string sql = CreateSql(selectedViewName);
            frmReportViewer rep = new frmReportViewer();
            rep.Source = new Database().LoadDt(sql);
            rep.Text = selectedViewCaption;
            rep.Show();
        }


    }

    public class ReportColumn
    {
        public enum Filtre
        {
            Eşittir,
            Büyüktür,
            BüyükEşittir,
            Küçüktür,
            KüçükEşittir,
            İçerir,
            İçermez
        }
        public string Name { get; set; }
        public DbType Type { get; set; }
        public Filtre FiltreTipi { get; set; }
        public string Value { get; set; }
    }
}
